package com.hsgene.product.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hsgene.common.DeleteFlagType;
import com.hsgene.common.util.basic.JsonUtils;
import com.hsgene.common.util.qiniu.QiniuCertificateUtil;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.product.condition.CommentCondition;
import com.hsgene.product.constants.CommentType;
import com.hsgene.product.constants.ReplyAdminType;
import com.hsgene.product.constants.ReplyType;
import com.hsgene.product.domain.GeneticComment;
import com.hsgene.product.domain.GeneticCommentReply;
import com.hsgene.product.dto.CommentPackageDto;
import com.hsgene.product.dto.GeneticCommentDto;
import com.hsgene.product.dto.GeneticCommentPageDto;
import com.hsgene.product.dto.GeneticTestingCommodityDetailDto;
import com.hsgene.product.persistence.GeneticCommentMapper;
import com.hsgene.product.persistence.GeneticCommentReplyMapper;
import com.hsgene.product.service.CommentService;
import com.hsgene.product.service.CommodityService;
import com.hsgene.product.service.api.GeneratorService;
import com.hsgene.product.service.api.UserService;
import com.hsgene.user.dto.user.GeneticTestingUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: //TODO
 * @ProjectName: hdas-geneshop
 * @Package: com.hsgene.product.service.impl
 * @Author: FX
 * @CreateDate: 2018/10/19 10:09
 * @Version: 1.0
 * Copyright: Copyright (c) 2018
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Resource
    GeneratorService generatorService;
    @Autowired
    GeneticCommentReplyMapper replyMapper;
    @Autowired
    GeneticCommentMapper commentMapper;
    @Autowired
    CommodityService commodityService;
    @Autowired
    UserService userService;
    private final static Logger LOGGER = LoggerFactory.getLogger(CommodityServiceImpl.class);

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult addGeneticCommentReply(GeneticCommentReply geneticCommentReply) {
        ApiResult<GeneratorDto> generator = generatorService.getGenerator(null, null);
        if (!generator.isSucc()) {
            return ApiResult.fail(generator.getError());
        }
        geneticCommentReply.setId(generator.getData().getSerialNumber());
        geneticCommentReply.setReplyType(ReplyType.REPLYTO_ACOMMENT.getCode());
        geneticCommentReply.setIsAdmin(ReplyAdminType.REPLY_REPLY.getCode());
        geneticCommentReply.setDeleteFlag(DeleteFlagType.NOT_DELETED.getCode());
        geneticCommentReply.setCreateDateTime(new Date());

        replyMapper.insertSelective(geneticCommentReply);
        //修改评论表状态
        GeneticComment geneticComment = new GeneticComment();
        geneticComment.setIsReply(1);
        geneticComment.setId(geneticCommentReply.getCommentId());
        commentMapper.updateByPrimaryKeySelective(geneticComment);
        return ApiResult.succ();
    }

    @Override
    public ApiResult<GeneticCommentDto> getCommentById(String id) {
        GeneticComment geneticComment = commentMapper.selectByPrimaryKey(id);
        GeneticCommentDto geneticCommentDto = new GeneticCommentDto();
        BeanUtils.copyProperties(geneticComment, geneticCommentDto);
        //回复图片
        if (!StringUtils.isEmpty(geneticComment.getImagesUrl())) {
            try {
                List<String> strings = JsonUtils.jsonToObject(geneticComment.getImagesUrl(), new
                        TypeReference<List<String>>() {
                        });
                geneticCommentDto.setImagesUrlList(QiniuCertificateUtil.getDownloadCertificateList(strings));
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.error("评论id = {}的详情图片数据格式异常，不符合JSON格式", id);
                geneticCommentDto.setImagesUrlList(null);
            }
        }
        //获取商品信息
        ApiResult<Object> commodityByPackageId = commodityService.findCommodityByPackageId(geneticComment
                .getPackageId());
        if (!commodityByPackageId.isSucc()) {
            return ApiResult.fail(commodityByPackageId.getError());
        }
        GeneticTestingCommodityDetailDto data = (GeneticTestingCommodityDetailDto) commodityByPackageId.getData();
        CommentPackageDto commentPackageDto = new CommentPackageDto();
        //commentPackageDto.setImagesUrl(data.getDetailImagesUrl());
        commentPackageDto.setDetectionPrice(data.getPackageInfo().getGeneticTestingProduct().getDetectionPrice());
        commentPackageDto.setDiscountPrice(data.getDiscountPrice());
        commentPackageDto.setTags(data.getTags());
        commentPackageDto.setPackageName(data.getPackageInfo().getPackageName());
        commentPackageDto.setCommodityCategoryLabel(data.getCommodityCategoryLabel());
        geneticCommentDto.setCommentPackageDto(commentPackageDto);
        geneticCommentDto.setGoodsImage(QiniuCertificateUtil.getOneDownloadCertificate(data.getImagesUrl()));
        //用户信息
        ApiResult<GeneticTestingUserDto> userInfo = userService.getUserInfo(geneticComment.getUserId());
        if (!userInfo.isSucc()) {
            return ApiResult.fail(userInfo.getError());
        }
        geneticCommentDto.setPhone(userInfo.getData().getPhone());
        //回复内容
        GeneticCommentReply commentReply=replyMapper.getByCommentId(id);
        if(commentReply!=null){
            geneticCommentDto.setReplyContent(commentReply.getContent());
        }
        return ApiResult.succ(geneticCommentDto);
    }

    /***
     * 商品评价列表
     * @author jcl
     * @date 2018/10/19 15:05
     * @param condition 查询条件
     * @return
     */
    @Override
    public ApiResult comments(CommentCondition condition) {
        FieldChecker.checkEmpty(condition.getLimitHelper(), "分页条件");
        int count = commentMapper.commentCount(condition);
        Pagination<GeneticCommentPageDto> pagination = Pagination.newInstance(condition.getLimitHelper(), count);
        List<GeneticCommentPageDto> commentDtos = new ArrayList<>();
        if (count > 0) {
            commentDtos = commentMapper.comments(condition);
            if (commentDtos != null && commentDtos.size() > 0) {
                int rowNum = (condition.getLimitHelper().getPage() - 1) * condition.getLimitHelper().getSize();
                for (int i = 0; i < commentDtos.size(); i++) {
                    GeneticCommentPageDto commentDto = commentDtos.get(i);
                    if(!StringUtils.isEmpty(commentDto.getPackageImageUrl())){
                        String packageImageUrl = QiniuCertificateUtil.getOneDownloadCertificate(commentDto.getPackageImageUrl());
                        commentDto.setPackageImageUrl(packageImageUrl);
                    }
                    commentDto.setReplyDesc(CommentType.commentType(commentDto.getIsReply()));
                    commentDto.setNumber(rowNum + 1 + i);
                }
            }
        }
        pagination.setResult(commentDtos);
        return new ApiResult(200, "success", "获取数据成功", pagination);
    }
}
